<?php
namespace app\system\controller;

use app\common\logic\CmsFieldLogic;
use app\common\model\CmsFieldModel;
use app\common\model\UserModel;
use think\Db;
use think\helper\Str;
use think\Request;

class CmsController extends BaseController
{

    private $cid;
    private $mid;
    private $cmsMoudleCache;
    private $cmsMoudleName;
    private $cmsCategoryCache;
    private $cmsFieldModel;
    private $cmsFieldLogic;
    private $cmsModel;
    private $tableName;

    /**
     * 初始化
     */
    public function __construct(Request $request)
    {
        parent::__construct($request);
        $this->cid              = $this->request->param('cid/d', 0);
        $this->mid              = $this->request->param('mid/d', 0);
        $this->cmsMoudleCache   = cache('cms_moudle');
        $this->cmsCategoryCache = $this->getCategory();
        $this->cmsFieldModel    = new CmsFieldModel();
        $this->cmsFieldLogic    = new CmsFieldLogic($this->getUid(), $this->getSiteId());
        if ($this->mid > 0) {
            $this->cmsModel      = cms_moudle($this->mid);
            $this->cmsMoudleName = $this->cmsMoudleCache[$this->mid]['moudle_name'];
            $this->tableName     = $this->cmsMoudleCache[$this->mid]['table_name'];
        }
    }

    /**
     * 获取允许操作栏目
     * @param $siteId
     * @param $uid
     * @return array|mixed
     */
    public function getCategory(){
        $userModel = new UserModel();
        $category = $userModel->getCmsCategory($this->getGroupId());
        return $category;
    }

    //内容管理首页
    public function iframe()
    {
        return $this->fetch();
    }

    /**
     * ajax zTree树型
     */
    public function ajaxztree()
    {
        $cate     = $this->cmsCategoryCache;
        $category = [];
        if ($cate) {
            $catTypeName = ['1' => '(频道)', '2' => '(列表)', '3' => '(外链)'];
            foreach ($cate as $cat) {
                $data         = [];
                $data['name'] = $cat['cat_name'] . $catTypeName[$cat['cat_type']];
                switch ($cat['cat_type']) {
                    case '1':
                        $url = 'javascript:;';
                        break;
                    case '2':
                        $url = url('index', ['cid' => $cat['cid'], 'mid' => $cat['mid']]);
                        break;
                    case '3':
                        $url = 'javascript:;';
                        break;
                }
                $data['id']     = $cat['cid'];
                $data['pId']    = $cat['pid'];
                $data['url']    = $url;
                $data['target'] = 'iframecms';
                if ($cat['_level'] == 2 && $cat['is_son'] == true) {
                    $data['open'] = false;
                } else {
                    $data['open'] = true;
                }
                $category[] = $data;
            }
        }
        return json($category);
    }

    /**
     * 首页
     * @return mixed
     */
    public function index()
    {
        $map            = [];
        $query          = ['mid' => $this->mid, 'cid' => $this->cid];
        $map['site_id'] = $this->getSiteId();
        $map['mid']     = $this->mid;
        $query['mid']   = $this->mid;
        $title          = $this->request->param('title');
        if (!empty($title)) {
            $map['title']   = ['like', '%' . $title . '%'];
            $query['title'] = $title;
        }
        if ($this->cid > 0) {
            $cids         = array_keys(\org\util\TreeUtil::channelList($this->cmsCategoryCache, $this->cid, "&nbsp;", 'cid', 'pid'));
            $cids[]       = $this->cid; //加入当前栏目
            $map['cid']   = ['in', $cids];
            $query['cid'] = $this->cid;
        }
        $list = $this->cmsModel->where($map)->order('sort desc,aid desc')->paginate(10, false, [
            'query' => $query,
        ]);
        //echo $this->cmsModel->getLastSql();
        $flagList = $this->cmsFieldModel->getFlaglist($this->mid);
        $this->assign('category',$this->cmsCategoryCache);
        $this->assign('flagList', $flagList);
        $this->assign('moudleName', $this->cmsMoudleName);
        $this->assign('query', $query);
        $this->assign('list', $list);
        if (file_exists(APP_PATH . 'system/view/cms/index_' . $this->tableName . '.html')) {
            return $this->fetch('index_' . $this->tableName);
        } else {
            return $this->fetch();
        }
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isAjax()) {
            $data   = $this->request->param();
            $result = $this->validate($data, Str::studly($this->tableName) . 'Validate.add');
            if (true !== $result) {
                $this->error($result);
            }
            $data['description'] = empty($data['description'])?' ':$data['description'];
            if (!$this->request->has('flag')) {
                $data['flag'] = '';
            }
            $data['site_id'] = $this->getSiteId();
            $data['uid'] = $this->getUid();
            $this->cmsModel->isUpdate(false)->allowField(true)->save($data);
            $this->success('添加成功！', url('index', ['mid' => $this->mid, 'cid' => $this->cid]));
        }
        $layoutForm = $this->cmsFieldLogic->getHtml();
        $this->assign('layoutForm', $layoutForm);
        $this->assign('moudleName', $this->cmsMoudleName);
        if (file_exists(APP_PATH . 'system/view/cms/add_' . $this->tableName . '.html')) {
            $outHtml = $this->fetch('add_' . $this->tableName);
        } else {
            $outHtml = $this->fetch();
        }
        return $this->display($outHtml);
    }

    /**
     * 修改
     * @return mixed
     */
    public function edit()
    {
        if ($this->request->isAjax()) {
            $data   = $this->request->param();
            $result = $this->validate($data, Str::studly($this->tableName) . 'Validate.edit');
            if (true !== $result) {
                $this->error($result);
            }
            if (!$this->request->has('flag')) {
                $data['flag'] = '';
            }
            if (!$this->request->has('extend')) {
                $data['extend'] = '';
            }
            $this->cmsModel->isUpdate(true)->allowField(true)->save($data);
            $this->success('修改成功！', url('index', ['mid' => $this->mid, 'cid' => $this->cid]));
        }
        $aid        = $this->request->param('aid');
        $info       = $this->cmsModel->get($aid)->toArray();
        $layoutForm = $this->cmsFieldLogic->getHtml($info);
        $this->assign('layoutForm', $layoutForm);
        $this->assign('moudleName', $this->cmsMoudleName);
        if (file_exists(APP_PATH . 'system/view/cms/edit_' . $this->tableName . '.html')) {
            $outHtml = $this->fetch('edit_' . $this->tableName);
        } else {
            $outHtml = $this->fetch();
        }
        return $this->display($outHtml);
    }

    /**
     * 删除
     */
    public function del()
    {
        $aid = $this->request->param('aid');
        if(is_numeric($aid)){
            $this->cmsModel->destroy($aid);
        }else{
            $aids = explode(',',$aid);
            foreach ($aids as $aid){
                $this->cmsModel->destroy($aid);
            }
        }
        $this->success('删除成功！');
    }

    /**
     * 排序
     */
    public function upOrder()
    {
        $sort = $this->request->param('sort/a');
        if (!empty($sort)) {
            foreach ($sort as $k => $v) {
                $dataList[] = ['aid' => (int)$k, 'sort' => (int)$v];
            }
            $this->cmsModel->saveAll($dataList);
            $this->success('排序成功', url('index'));
        } else {
            $this->error('参数错误！');
        }
    }
    /**
     * 设置模板
     */
    public function setTpl()
    {
        $tpl = $this->request->param('tpl/a');
        if (!empty($tpl)) {
            foreach ($tpl as $k => $v) {
                $dataList[] = ['aid' => (int)$k, 'content_tpl' => $v];
            }
            $this->cmsModel->saveAll($dataList);
            $this->success('模板设置成功', url('index'));
        } else {
            $this->error('参数错误！');
        }
    }

    /**
     * 更新审核状态
     */
    public function setStatus()
    {
        $aid    = $this->request->param('aid');
        $status = $this->request->param('status/d');
        $this->cmsModel->where('aid', 'in', $aid)->setField('status', $status);
        $this->success('操作成功！');
    }

    /**
     * 设置状态
     */
    public function setFlag()
    {
        $action = $this->request->param('action');
        $aids   = $this->request->param('aid');
        $flag   = $this->request->param('flag');
        $aids   = explode(',', $aids);
        foreach ($aids as $aid) {
            $map['aid'] = $aid;
            $oldFlag    = $this->cmsModel->where($map)->value('flag');
            if ($action == 'set') {
                if (empty($oldFlag)) {
                    $newFlag = $flag;
                } else {
                    $newFlag = $oldFlag . ',' . $flag;
                }
            } else { //取消
                $oldFlag = str_replace($flag, '', $oldFlag);
                $newFlag = str_replace(',,', ',', $oldFlag);
            }
            Db::table($this->tableName)->where('aid', $aid)->update(['flag' => $newFlag]);
        }
        $this->success('操作成功！');
    }

}
